import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(MaterialApp(home: WebViewExample()));

String initUrl = 'http://vip.lcmsh.com';

String getCouponJs = '''
                        \$.ajax({
                                type: "post",
                                url: "/ashx/shop.ashx",
                                data: "action=savegoods&goodsid=1533&number=1",
                                dataType: "json",
                                timeout: 60000,
                                success: function (data) {
                                    Toaster.postMessage(JSON.stringify(data))
                                },
                                error: function(xhr,state,errorThrown){
                                    Toaster.postMessage("领取失败")
                                }
                            })
                        ''';
// String doPayJs = '''
//               (function () {
//                 // 判断是否缴费
//                 var setfree = parseInt(\$("#totalMoney").html());
//                 var zz = setfree;
//                 if (setfree == 0) {
//                     Toaster.postMessage("CALL2:您已缴费 ");
//                     return;
//                 }
//
//                 window.maxIntegral = 80000;
//
//                 //选中优惠券
//                 \$('input[name="cardRadio"]').prop('checked', true);
//                 \$("#couponPrice").html(9);
//
//                 setfree = parseInt(\$("#totalMoney").html());
//                 //使用积分
//                 while (setfree > 0) {
//                     usePoint(1);
//                     setfree = parseInt(\$("#totalMoney").html());
//                 }
//                 //设置积分为0
//                 \$("#sendPoint").val(0);
//                 // 获取车牌号和优惠券码，进行支付
//                 var car_no = window.location.href.substr(window.location.href.lastIndexOf('=') + 1, window.location.href.length);
//                 var ticketno = \$(":checkbox[name='cardRadio']")[0].getAttribute('data-code');
//                 \$.ajax({
//                     type: 'POST',
//                     url: "http://vip.lcmsh.com/car_park_normal/pay?mt=cashPay&parkID=88&integral=0&fee=" + zz + "&car_no=" + car_no + "&payNo=&ticketno=" + ticketno,
//                     data: "",
//                     dataType: "json",
//                     success: function (data) {
//                         Toaster.postMessage("CALL2:付费结果:" + JSON.stringify(data));
//                     }
//                 });
//               })()
//             ''';

    payJs(bool isHoliday){
      if (isHoliday){
        return '''
              (function () {
                // 判断是否缴费
                var setFree = parseInt(\$("#totalMoney").html());
                if (setFree == 0) {
                    Toaster.postMessage("CALL2:您已缴费 ");
                    return;
                }
            
                // 获取车牌号和优惠券码，进行支付
                var car_no = window.location.href.substr(window.location.href.lastIndexOf('=') + 1, window.location.href.length);
                \$.ajax({
                    type: 'POST',
                    url: "http://vip.lcmsh.com/car_park_normal/pay?mt=cashPay&parkID=88&integral=200&fee=" + setFree + "&car_no=" + car_no + "&payNo=&ticketno=" + ticketno,
                    data: "",
                    dataType: "json",
                    success: function (data) {
                        Toaster.postMessage("CALL2:付费结果:" + JSON.stringify(data));
                    }
                });
              })()
            ''';
      } else {
        return '''
              (function () {
                // 判断是否缴费
                var setfree = parseInt(\$("#totalMoney").html());
                var zz = setfree;
                if (setfree == 0) {
                    Toaster.postMessage("CALL2:您已缴费 ");
                    return;
                }
            
                window.maxIntegral = 80000;
            
                //选中优惠券
                \$('input[name="cardRadio"]').prop('checked', true);
                \$("#couponPrice").html(9);
            
                setfree = parseInt(\$("#totalMoney").html());
                //使用积分
                while (setfree > 0) {
                    usePoint(1);
                    setfree = parseInt(\$("#totalMoney").html());
                }
                //设置积分为0
                \$("#sendPoint").val(0);
                // 获取车牌号和优惠券码，进行支付
                var car_no = window.location.href.substr(window.location.href.lastIndexOf('=') + 1, window.location.href.length);
                var ticketno = \$(":checkbox[name='cardRadio']")[0].getAttribute('data-code');
                \$.ajax({
                    type: 'POST',
                    url: "http://vip.lcmsh.com/car_park_normal/pay?mt=cashPay&parkID=88&integral=0&fee=" + zz + "&car_no=" + car_no + "&payNo=&ticketno=" + ticketno,
                    data: "",
                    dataType: "json",
                    success: function (data) {
                        Toaster.postMessage("CALL2:付费结果:" + JSON.stringify(data));
                    }
                });
              })()
            ''';
      }
    }

    String testJS = 'Toaster.postMessage("测试JS执行");';


    simpleJs(String js){
      return '''
        (function () {
          $js
        })()
        ''';
    }


class WebViewExample extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter WebView example'),
        // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
        actions: <Widget>[
          NavigationControls(_controller.future),
          SampleMenu(_controller.future),
        ],
      ),
      // We're using a Builder here so we have a context that is below the Scaffold
      // to allow calling Scaffold.of(context) so we can show a snackbar.
      body: Builder(builder: (BuildContext context) {
        return WebView(
          // 初始URL设置
          initialUrl: initUrl,
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller.complete(webViewController);
          },
          // onProgress: (int progress) {
          //   print("WebView is loading (progress : $progress%)");
          // },
          javascriptChannels: <JavascriptChannel>{
            _toasterJavascriptChannel(context),
          },
          // navigationDelegate: (NavigationRequest request) {
          //   if (request.url.startsWith('http://vip.lcmsh.com')) {
          //     print('blocking navigation to $request}');
          //     return NavigationDecision.prevent;
          //   }
          //   print('allowing navigation to $request');
          //   return NavigationDecision.navigate;
          // },
          onPageStarted: (String url) {
            print('Page started loading: $url');
          },
          onPageFinished: (String url) {
            print('Page finished loading: $url');
          },
          gestureNavigationEnabled: true,
        );
      }),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}

enum MenuOptions {
  logout,
  toBaidu,
  toGitee,
  getCoupon,
  doPay,
  doPayHoliday,
  oneKey,
  test,
}

class SampleMenu extends StatelessWidget {
  SampleMenu(this.snapshot);

  final Future<WebViewController> snapshot;
  final CookieManager cookieManager = CookieManager();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
      future: snapshot,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
        return PopupMenuButton<MenuOptions>(
          onSelected: (MenuOptions value) {
            // final bool webViewReady =snapshot.connectionState == ConnectionState.done;
            final WebViewController controller = snapshot.data;
            switch (value) {
              case MenuOptions.logout:
                controller.clearCache();
                break;
              case MenuOptions.toBaidu:
                controller.loadUrl("https://www.baidu.com");
                break;
              case MenuOptions.toGitee:
                controller.loadUrl("https://www.gitee.com");
                break;
              case MenuOptions.getCoupon:
                controller.evaluateJavascript(getCouponJs);
                break;
              case MenuOptions.doPay:
                controller.evaluateJavascript(payJs(false));
                break;
              case MenuOptions.doPayHoliday:
                controller.evaluateJavascript(payJs(true));
                break;
              case MenuOptions.oneKey:
                controller
                    .evaluateJavascript(getCouponJs)
                    .whenComplete(() => {controller.reload()})
                    .whenComplete(() => controller.evaluateJavascript(payJs(false)))
                    .whenComplete(() => controller.reload());
                break;
              case MenuOptions.test:
                controller.evaluateJavascript(simpleJs(testJS));
                break;
            }
          },
          itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
            PopupMenuItem<MenuOptions>(
              value: MenuOptions.logout,
              child: const Text('登出'),
              enabled: snapshot.hasData,
            ),
            const PopupMenuItem<MenuOptions>(
              value: MenuOptions.getCoupon,
              child: const Text('执行JS测试-领券'),
            ),
            const PopupMenuItem<MenuOptions>(
              value: MenuOptions.doPay,
              child: const Text('执行JS测试-付款'),
            ),
            const PopupMenuItem<MenuOptions>(
              value: MenuOptions.doPayHoliday,
              child: const Text('执行JS测试-假期付款'),
            ),
            const PopupMenuItem<MenuOptions>(
              value: MenuOptions.test,
              child: const Text('测试JS'),
            ),
            // const PopupMenuItem<MenuOptions>(
            //   value: MenuOptions.oneKey,
            //   child: const Text('执行JS测试'),
            // ),
          ],
        );
      },
    );
  }
}

class NavigationControls extends StatelessWidget {
  const NavigationControls(this._webViewControllerFuture)
      : assert(_webViewControllerFuture != null);

  final Future<WebViewController> _webViewControllerFuture;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
      future: _webViewControllerFuture,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
        final bool webViewReady =
            snapshot.connectionState == ConnectionState.done;
        final WebViewController controller = snapshot.data;
        return Row(
          children: <Widget>[
            // 返回键UI
            IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: !webViewReady
                  ? null
                  : () async {
                      if (await controller.canGoBack()) {
                        await controller.goBack();
                      } else {
                        // ignore: deprecated_member_use
                        Scaffold.of(context).showSnackBar(
                          const SnackBar(content: Text("No back history item")),
                        );
                        return;
                      }
                    },
            ),
            // 向前键
            IconButton(
              icon: const Icon(Icons.arrow_forward_ios),
              onPressed: !webViewReady
                  ? null
                  : () async {
                      if (await controller.canGoForward()) {
                        await controller.goForward();
                      } else {
                        // ignore: deprecated_member_use
                        Scaffold.of(context).showSnackBar(
                          const SnackBar(
                              content: Text("No forward history item")),
                        );
                        return;
                      }
                    },
            ),
            // 刷新键
            IconButton(
              icon: const Icon(Icons.replay),
              onPressed: !webViewReady
                  ? null
                  : () {
                      controller.reload();
                    },
            ),
          ],
        );
      },
    );
  }
}
